package org.visionlibrary.image.filters.adjustement;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class AdaptiveMaximumRGB extends AbstractFilter {
	protected int tolerance = 10;

	public AdaptiveMaximumRGB() {
		this(10);
	}

	public AdaptiveMaximumRGB(int tolerance) {
		this.tolerance = tolerance;
	}

	@Override
	public TiledImage applyFilter(TiledImage src, TiledImage dest) {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src);

		int maxX = src.getWidth();
		int maxY = src.getHeight();

		for (int x = 0; x < maxX; x++)
			for (int y = 0; y < maxY; y++) {
				int maxchannel = 0;
				int channel = 0;
				for (int ch = 0; ch < src.getNumBands(); ch++) {
					int c = src.getSample(x, y, ch);
					if (maxchannel < c) {
						maxchannel = c;
						channel = ch;
					}
				}

				for (int ch = 0; ch < src.getNumBands(); ch++) {
					int c = src.getSample(x, y, ch);
					if (maxchannel - tolerance <= c) {
						dest.setSample(x, y, ch, 255);
					} else {
						dest.setSample(x, y, ch, 0);
					}
				}
				dest.setSample(x, y, channel, 255);
			}

		return dest;
	}

	public int getTolerance() {
		return tolerance;
	}

	public void setTolerance(int tolerance) {
		this.tolerance = tolerance;
	}
	
	@Override
	public String toString() {
		return new String("Adjustement>Adaptive Maximum RGB");
	}
}
